import axios from 'axios'

export default {
    namespaced: true,
    state() {
        return {
            list: []
        }
    },
    mutations: {
        updateList(state, newList) {
            state.list = newList
        },
        updateCount(state, obj) {
            // console.log(obj)
            // 根据 id 找到对应的对象，更新 count
            const goods = state.list.find(item => item.id === obj.id)
            goods.count = obj.newCount
            // console.log(goods.count)
        }
    },
    actions: {
        async getList(context) {
            const res = await axios.get('http://localhost:3000/cart')
            // console.log(res)
            context.commit('updateList', res.data)
        },
        async updateCountAsync(context, obj) {
            // 调用接口，修改后台数据
            const res = await axios.patch(`http://localhost:3000/cart/${obj.id}`, {
                count: obj.newCount
            })
            // console.log(res.data)
            // 我们这里使用后台传过来的数据
            const {id, count} = res.data
            // 将更新修改到 vuex
            context.commit('updateCount', {
                id,
                newCount: count
            })
        }
    },
    getters: {
        // 总数
        totalCount(state) {
            return state.list.reduce((sum, item) => sum + item.count, 0)
        },
        // 总价
        totalPrice(state) {
            return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
        }
    }
}
